package com.personal.core.exchange;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class Convertor<O, T>
{
    private ConvertionClassInfo classInfo = new ConvertionClassInfo();

    public Convertor()
    {
        analzyeGenericClasses();
    }

    public T exchangeType(O obj)
    {
        if (obj == null)
        {
            return null;
        }

        if (!examType(obj))
        {
            return null;
        }

        return exchange(obj);
    }

    public abstract T exchange(O paramO);

    public boolean examType(Object obj)
    {
        if (obj == null)
        {
            return true;
        }

        return obj.getClass() == this.classInfo.getOrginalClass();
    }

    protected void analzyeGenericClasses()
    {
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();

        if (parameterizedType != null)
        {
            Type[] genericTypes = parameterizedType.getActualTypeArguments();

            if (genericTypes.length >= 2)
            {
                if ((genericTypes[0] instanceof Class))
                {
                    this.classInfo.setOrginalClass((Class) genericTypes[0]);
                }
                if ((genericTypes[1] instanceof Class))
                {
                    this.classInfo.setTransformClass((Class) genericTypes[1]);
                }
            }
        }
    }

    public ConvertionClassInfo getClassInfo()
    {
        return this.classInfo;
    }
}